package main;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import sintacticAnalysis.SintacticAnalysis;
import sintacticAnalysis.SintaxErrorException;
import elements.Vocabulary;
import lexicalAnalysis.LexicalAnalysis;
import lexicalAnalysis.LexicalException;

/**
 * Clasa ce se ocupa de analiza sintactica si lexicala
 *
 */
public class Analysis {
	protected LexicalAnalysis la;
	protected int index;
	protected Vocabulary voc;
	protected ArrayList<String> lines;
	protected SintacticAnalysis sa;
	protected WriteFile wf;

	public Analysis() throws IOException {
		lines = ReadFile.readFromFile("scenariu.txt");
		wf = new WriteFile("errorlog.txt");
		BufferedWriter bw=new BufferedWriter(new FileWriter("errorlog.txt"));
		bw.write("");
		bw.close();
		la = new LexicalAnalysis();
		sa = new SintacticAnalysis();
		voc = new Vocabulary();
		index = 0;
	}

	/**
	 *verifica corectitudinea scenariului
	 */
	public void verify() throws LexicalException, SintaxErrorException,
	IOException {
		Iterator<String> it = lines.iterator();
		String[] tokens;
		String elem;

		while (it.hasNext()) {
			elem = it.next();
			if (elem.startsWith("Creaza"))
			{
				tokens=splitLine(elem);
				if (!voc.getIncaperi().contains(tokens[1]))
				{
					voc.setName(tokens[1]);
				}
				
				continue;
			}
			else
				if (elem.startsWith("Adauga"))
					continue;
				else
				{
					try {
						tokens = splitLine(elem);
						try{
							la.verifyBelonging(tokens, index);
						}catch(Exception e)
						{
							wf.write(e.getMessage());
						}
						try{
							sa.matchPattern(tokens, index);
						}catch(Exception e)
						{
							wf.write(e.getMessage());
						}

					} catch (Exception e) {

					}
				}
			index++;
		}
	}

	/**
	 * imparte o linie din tabel in cuvinte
	 */
	public String[] splitLine(String line) throws LexicalException, IOException {
		String aux = determineCompositions(line);
		String tokens[] = null;

		tokens = aux.split(" ");
		for (int i = 0; i < tokens.length; i++) {
			tokens[i] = tokens[i].replace('*', ' ');
		}
		return tokens;
	}

	public String determineCompositions(String line) {

		ArrayList<String> composed = voc.getComposed();
		Iterator<String> itr = composed.iterator();
		int index1 = 0, index2 = 0, spaceIndex = 0;
		String element;

		while (itr.hasNext()) {
			element = itr.next();
			if ((index1 = line.indexOf(element)) >= 0) {
				index2 = index1 + element.length();
				for (spaceIndex = index1; spaceIndex < index2; spaceIndex++) {
					if (line.charAt(spaceIndex) == ' ')
						line = line.substring(0, spaceIndex) + "*"
						+ line.substring(spaceIndex + 1);
				}
			}
		}
		return line;
	}
}
